<?php 
namespace Admin\Controller;
use Admin\Controller\BaseController;
use Think\Model;
/**
* 
*/
class WechatController extends BaseController{
	function config(){
		if(IS_POST){
			$arr = I('post.');
			$data = [
				'WX_APPID' => $arr['appid'],
				'WX_SECRET' => $arr['appsecret'],
				'WX_URL_TOKEN' => $arr['urltoken'],
				'WX_ENCODE_STR' => $arr['encodestr'],
				'WX_WEL_STR' => $arr['welstr'],
				'WX_REWEL_STR' => $arr['rewelstr'],
			];
			$config_old = require C('CONF_PATH').'/wechat.php';
			$config_new = array_merge($config_old,$data);
			arr2file(C('CONF_PATH').'/wechat.php',$config_new);
			$this->success("设置成功，稍等为您跳转");
		}else{
			$this->wechat = [
				'appid' => C('WX_APPID'),
				'appsecret' => C('WX_SECRET'),
				'urltoken' => C('WX_URL_TOKEN'),
				'encodestr' => C('WX_ENCODE_STR'),
				'welstr' => C('WX_WEL_STR'),
				'rewelstr' => C('WX_REWEL_STR'),
			];
			$this->display('wechat-config');	
		}
	}

	function wechatbtn(){
		$BTN = new Model('Wxbtn');
		$btnlist_top = $BTN->where(['pid'=>0])->select();
		$btnlist_son = $BTN->where(['pid'=>['neq',0]])->select();
		$this->assign('btntop',$btnlist_top);
		$this->assign('btnson',$btnlist_son);
		$this->display('wechat-btn');	
	}

	function insertbtn(){
		if(IS_POST){
			$BTN = D('Wxbtn');
            if(!$BTN->create()){
                $this->error($BTN->getError());
            } else {
                $rs = $BTN->add();
                if($rs !== FALSE){
                	if(I('pid') > 0){
                		$BTN->where(['id'=>I('pid')])->setInc('sub',1);
                	}
                    $this->success('增加成功');
                } else {
                    $this->error('增加失败');
                }
            }
		}else{
			$BTN = new Model('Wxbtn');
			$btnlist_top = $BTN->where(['pid'=>0])->select();
			$this->assign('btntop',$btnlist_top);
			$this->display('wechat-insertbtn');
		}
	}

	function editbtn(){
		if(IS_POST){
			$id = I('id','');
	        if($id == ''){
	            $this->error('参数错误');
	        } else {
	        	$map['id'] = $id;
	        	if(I('name') != ''){
	        		$map['name'] = I('name');
	        	}
	        	$map['pid'] = I('pid');
	        	$map['type'] = I('type');
	        	if(I('click') != ''){
	        		$map['click'] = I('click');
	        	}
	        	if(I('url') != ''){
	        		$map['url'] = I('url');
	        	}
	        	$map['status'] = I('status');
	        	$BTN = D('Wxbtn');
	        	$tmp = $BTN->where(['id'=>$id])->find();
	        	if(!$BTN->create($map)){
                    $this->error($BTN->getError());
                } else {
                    $rs = $BTN->save();
                    if($rs !== FALSE){
                    	if($tmp['pid'] > 0){
                    		$BTN->where(['id'=>$tmp['pid']])->setDec('sub',1);
                    		if($map['pid'] > 0){
                    			$BTN->where(['id'=>$map['pid']])->setInc('sub',1);
                    		}
                    	}
                        $this->success('编辑成功');
                    } else {
                        $this->error('编辑失败');
                    }
                }
	        }
		}else{
			$id = I('id','');
	        if($id == ''){
	            $this->error('参数错误');
	        } else {
	        	$BTN = new Model('Wxbtn');
	        	$edit = $BTN->where(['id'=>$id])->find();
	        	if($edit){
	        		$btnlist_top = $BTN->where(['pid'=>0])->select();
	        		$this->assign('btntop',$btnlist_top);
	        		$this->assign('edit',$edit);
	        		$this->display('wechat-editbtn');
	        	}else{
	        		$this->error('记录不存在');
	        	}
	        }
		}
	}

	function deletebtn(){
		$id = I('id','');
        if($id == ''){
            $this->error('参数错误');
        } else {
            #判断如果是顶级是否有子菜单
            $BTN = new Model('Wxbtn');
            $one = $BTN->where(['id'=>$id])->find();
            if($one && $one['sub'] == 0){
	            $rs = $BTN->where(['id'=>$id])->delete();
	            if($rs !== FALSE){
	            	if($one['pid'] > 0){
	            		$BTN->where(['id'=>$one['pid']])->setDec('sub',1);
	            	}
	                $this->success('删除成功');
	            } else {
	                $this->error($BTN->getDbError());
	            }
	        }else{
	        	$this->error('记录不存在或者此菜单下有子菜单');
	        }
        }
	}

	function status(){
        $id = I('id','');
        $op = I('op') ? 1 : 0;
        if($id != ''){
            $BTN = new Model('Wxbtn');
            $rs = $BTN->where(['id'=>$id])->setField('status',$op);
            if($rs !== false){
                $this->success('操作成功');
            }else{
                $this->error('操作失败，稍后再试');
            }
        }else{
            $this->error('参数错误');
        }
    }

	function creatmenu(){
		#生成自定义菜单文件并保存
		#1，读取自定义菜单数据
		$BTN = new Model('Wxbtn');
		$btnlist_top = $BTN->where(['pid'=>0,'status'=>1])->limit(3)->order('id desc')->select();
		$menu = [];
		for ($i=0; $i < count($btnlist_top); $i++) { 
			#判断顶级菜单是否有下级菜单并相应处理
			if($btnlist_top[$i]['sub'] > 0){
				$son = [];
				#读取子菜单
				$btnlist_son = $BTN->where(['pid'=>$btnlist_top[$i]['id'],'status'=>1])->select();
				for ($k=0; $k < count($btnlist_son); $k++) { 
					if($btnlist_son[$k]['type'] == 0){
						$son[$k] = [
							'type' => 'click',
							'name' => $btnlist_son[$k]['name'],
							'key' => $btnlist_son[$k]['click'],
						];
					}else{
						$son[$k] = [
							'type' => 'view',
							'name' => $btnlist_son[$k]['name'],
							'url' => $btnlist_son[$k]['url'],
						];
					}
				}
				#构建菜单
				$menu[$i] = [
					'name' => $btnlist_top[$i]['name'],
					'sub_button' => $son,
				];
			}else{
				#没有子菜单的情况
				#判断菜单类型
				if($btnlist_top[$i]['type'] == 0){
					#click
					$menu[$i] = [
						'type' => 'click',
						'name' => $btnlist_top[$i]['name'],
						'key' => $btnlist_top[$i]['click'],
					];
				}else{
					$menu[$i] = [
						'type' => 'view',
						'name' => $btnlist_top[$i]['name'],
						'url' => $btnlist_top[$i]['url'],
					];
				}
			}
		}
		$rsp = $this->flushmenu($menu);
		$this->ajaxReturn($rsp,'json');
	}

	function flushmenu($menu){
		#刷新并同步到微信公众号
		$WechatAuth = new \Com\WechatAuth(C('WX_APPID'),C('WX_SECRET'),getWxToken());
		$rsp = $WechatAuth->menuCreate($menu);
		if(isset($rsp['errcode']) && $rsp['errcode'] == 0){
			return [
				'status' => true,
				'msg' => '',
			];
			//$this->success('同步成功，公众号存在缓存，预计24小时内完成同步或者更短，开发测试可以取关后再次关注可立即生效',U('admin/wechat/wechatbtn'));
		}else{
			return [
				'status' => false,
				'msg' => "同步失败，失败编码：{$rsp['errcode']}({$rsp['errmsg']})",
			];
			//$this->error("同步失败，失败编码：{$rsp['errcode']}({$rsp['errmsg']})",U('admin/wechat/wechatbtn'));
		}
	}


}